package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net"
	"net/http"
	"strconv"
	"time"
	//"github.com/gorilla/sessions"
	"os"

	"chatting/LoginInfo"
	"chatting/RegisterUserInfo"

	"golang.org/x/net/websocket"
)

const (
	SUCCESS               = 0x00
	USER_NAME_ERROR       = 0x01
	PASS_WORD_ERROR       = 0x02
	FAILED                = 0x04
	USER_EXISTENCE        = 0x05
	USER_LOGINED          = 0x06
	USERNAME_NULL         = 0x07
	USERNAME_LENGTH_ERROR = 0x08
	PASS_WORD_NULL        = 0x09
	PASS_LENGTH_ERROR     = 0x0a
	PASS_CMPARE_ERROR     = 0x0b
)

type Estruct struct {
	ErrorNumber string      `json:"errorNumber"`
	Statu       string      `json:"statu"`
	Info        interface{} `json:"info"`
}

var loginLabel bool

func ReportInfo(w http.ResponseWriter, errorNumber int) {
	errnoN := strconv.Itoa(errorNumber)
	statuN := strconv.Itoa(FAILED)
	messageInfo := Estruct{ErrorNumber: errnoN, Statu: statuN}
	Replay, _ := json.MarshalIndent(messageInfo, "", "\t\t")
	fmt.Fprint(w, string(Replay))
}
func ReportData(w http.ResponseWriter, data interface{}) {
	messageInfo := Estruct{Info: data}
	Replay, _ := json.MarshalIndent(messageInfo, "", "\t\t")
	fmt.Fprint(w, string(Replay))
}
func Login(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		t, _ := template.ParseFiles("login-er.html")
		t.Execute(w, nil)
		return
	} else {
		r.ParseForm()
		username := r.Form["username"][0]
		password := r.Form["password"][0]
		if err, user := RegisterUserInfo.SeekUser(username); err != nil {

			ReportInfo(w, USER_NAME_ERROR)
			return
		} else {
			if user.Password != password {
				ReportInfo(w, PASS_WORD_ERROR)
				return
			}
		}
		fmt.Println("userMap:", LoginInfo.LoginUserMap)
		err := LoginInfo.ProvingUser(username, password)
		fmt.Println("Error:", err)
		if err == nil {
			ReportInfo(w, USER_LOGINED)
			return
		}
		LoginTime := time.Now().Format("2006-01-02 15:04:05")
		ip := GetIP()
		fmt.Println("Ip:", ip)
		userInfo := LoginInfo.LoginUser{
			UserName: username,
			PassWord: password,
			Ws:       nil,
			Ip:       ip,
			Time:     LoginTime,
		}
		LoginInfo.Login(userInfo)
		loginLabel = true

		ReportData(w, username)
		return
		/*
			url := "/chat?username" + "=" + username
			http.Redirect(w, r, url, http.StatusFound)
			return
		*/
	}
}
func Register(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		t, _ := template.ParseFiles("register.html")
		t.Execute(w, nil)
	} else {

		r.ParseForm()
		fmt.Println("r.form:", r.Form.Encode())
		username := r.Form["username"][0]
		password := r.Form["password"][0]
		err, _ := RegisterUserInfo.SeekUser(username)
		if err == nil {

			ReportInfo(w, USER_EXISTENCE)
			return
		}
		userInfo := RegisterUserInfo.Registry{
			UId:      time.Now().Unix(),
			Username: username,
			Password: password,
			Online:   RegisterUserInfo.DefaultStatue,
			Language: "Chinese"}
		RegisterUserInfo.RegisterUser(userInfo)
		/*
			http.Redirect(w, r, "/login",302)
		*/
		return
	}

}
func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method)
	if r.Method == "GET" {
		t, _ := template.ParseFiles("ListName.html")
		/*
					data := struct {
				       Name string
			        }{
				   Name: "luominggao",
			        }
		*/
		//RegisterUserInfo.Registry
		user := []RegisterUserInfo.Registry{}
		userInfo := RegisterUserInfo.AllUserInfo()
		for _, userMsg := range userInfo.User {
			user = append(user, userMsg)
		}
		fmt.Println("user:", user)
		t.Execute(w, user)
	}
}
func serveHome(w http.ResponseWriter, r *http.Request) {
	if loginLabel == false {
		/*没有登录给予错误的提示消息，该路由访问不正确，NOT FOUND */
	}
	var homeTemplate = template.Must(template.ParseFiles("home.html"))
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	homeTemplate.Execute(w, r.Host)
}
func main() {
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	/*
		hub := newHub()
		go hub.run()
		http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
			serveWs(hub, w, r)
		})
	*/
	//http.Handle("/ws", websocket.Handler(BuildConnection))
	http.Handle("/ws", websocket.Handler(BuildConnection))
	http.HandleFunc("/chat", Chat)
	http.HandleFunc("/register", Register)
	http.HandleFunc("/login", Login)
	http.HandleFunc("/index", Index)
	//http.HandleFunc("/home", serveHome)
	go InitChatRoom()
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
func Chat(w http.ResponseWriter, r *http.Request) {
	username := r.URL.Query().Get("username")
	if r.Method == "GET" {
		t, _ := template.ParseFiles("chat.html")

		data := struct {
			UserName  string
			Websocket string
		}{
			UserName:  username,
			Websocket: r.Host,
		}
		fmt.Println("**********")
		t.Execute(w, data)
		return
	}
}
func GetIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		os.Exit(1)
	}
	for _, address := range addrs {
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}

		}
	}
	return ""

}
func getSession() {

}
func setSession(username, password string) {

}

/*
func Join(env Env) (status Status, headers Headers, body Body) {
	email := env.Request().FormValue("email")
	if email == "" {
		return Redirect(http.StatusFound, "/")
	}

	r := env.Request()
	mangotemplate.ForRender(env, "chats/room", &RenderData{Email: email, WebSocketHost: r.Host})
	headers = Headers{}
	return
}
*/
